<template>
  <div class="run-modal-style" style="height: 460px;">
    <!-- 搜索区域 -->
    <SelfAdaption>
      <Form
        :model="searchForm"
        ref="userSearchForm"
        slot="adaption-bar"
        label-position="top"
        class="ivu-form-no-margin-bottom"
        inline
      >
        <!-- 用户账号 -->
        <Form-item prop="userId" :label="$t('module.userManage.account')">
          <Input
            type="text"
            :maxlength="30"
            v-model.trim="searchForm.userId"
            :placeholder="$t('module.userManage.warning.enterUserAccount')"
            @on-enter="search"
          ></Input>
        </Form-item>
        <Form-item prop="userName" :label="$t('module.userManage.name')">
          <Input
            type="text"
            :maxlength="30"
            v-model.trim="searchForm.userName"
            :placeholder="$t('module.userManage.warning.enterUserName')"
            @on-enter="search"
          ></Input>
        </Form-item>
        <!-- 所属组织 -->
        <Form-item prop="orgName" :label="$t('module.userManage.organization')">
          <Input
            type="text"
            style="position: absolute; z-index: 999; opacity: 0; width: 80%;"
            @click.native="selectOrganization"
          ></Input>
          <Input
            type="text"
            :maxlength="30"
            v-model.trim="searchForm.orgName"
            :placeholder="$t('module.userManage.selectOrganization')"
            icon="ios-paper-plane-outline"
            clearable
            readonly
            @on-click="selectOrganization"
            @on-clear="clearSearchForm"
          ></Input>
        </Form-item>

        <!-- 查询\重置按钮 -->
        <Form-item prop="button" class="search-solt-btn">
          <RPButton optType="search" @click="search" />
          <RPButton optType="reset" @click="reset" />
        </Form-item>
      </Form>
    </SelfAdaption>
    <InnerPageTable ref="userTable" :config="tableConfig">
      <!--
      <div slot="handle-bar">
        <RPButton optType="search" @click="search" />
        <RPButton optType="reset" @click="reset" />
      </div>
      -->
    </InnerPageTable>
  </div>
</template>
<script>
import dataPermissionAPI from "@/api/dataPermissionAPI.js";
import locales from "./locales.js";
import { selectUserColumns } from "./columns.js";
import selectOrg from "../userCenter/userManage/selectOrganization.vue";
import { queryOrgsByOrgPaths } from "@/api/orgApi";

export default {
  name: "role-select-user",
  mixins: [locales],
  props: {
    tenantCode: {
      type: String,
      default() {
        return "";
      }
    },
    dimensionId: {
      type: String,
      default() {
        return "";
      }
    }
  },
  data() {
    return {
      searchForm: {
        tenantCode: this.tenantCode,
        policyDimensionRelId: this.dimensionId,
        userId: "",
        userName: "",
        orgName: "",
        orgPath: ""
      },
      actions: [
        {
          text: this.$t("common.confirm"),
          theme: "primary",
          handle: () => {
            this.onSaveClick();
          },
          loading: false
        },
        {
          text: this.$t("common.close"),
          handle: () => {
            this.$emit("Close");
          }
        }
      ]
    };
  },
  computed: {
    tableConfig() {
      return {
        loadDataFn: tableObj => {
          let { responseProcess, param } = tableObj;
          dataPermissionAPI.queryUnassignedUser(param).then(data => {
            let orgPaths = data.records.map(user => {
              return user.orgPath;
            });

            queryOrgsByOrgPaths(orgPaths).then(orgs => {
              data.records.forEach(user => {
                let userOrg = orgs.find(org => {
                  return org.orgPath == user.orgPath;
                });
                user._hasOrgInfo = true;
                if (userOrg) {
                  user.orgName = userOrg.orgName;
                  user.orgNameFullPath = userOrg.orgNameFullPath;
                } else {
                  user.orgName = user.orgPath;
                  user.orgNameFullPath = user.orgPath;
                }
              });
              tableObj.tableData = data.records;
            });
            responseProcess(data);
          });
        },
        autoFirst: true,
        columnsFn: selectUserColumns.bind(this),
        initParam: this.searchForm
      };
    }
  },
  created: function () {
    this.$emit("SetTitle", this.$t("module.post.selectUser"));
    this.$emit("SetPageWidth", 850);
    this.$emit("SetPageActions", this.actions);
  },
  methods: {
    selectOrganization() {
      new this.$pageModal(
        selectOrg,
        {
          props: {}
        },
        data => {
          if (data) {
            this.searchForm.orgPath = data.orgPath;
            this.searchForm.orgName = data.orgName;
          }
        }
      );
    },
    clearSearchForm() {
      this.searchForm.orgPath = "";
      this.searchForm.orgName = "";
    },
    search(page) {
      this.$refs["userTable"].load(this.searchForm, page);
    },
    reset() {
      this.$refs["userSearchForm"].resetFields();
      this.searchForm.orgPath = "";
      this.search(1);
    },
    onSaveClick() {
      // 如果未勾选，无需保存
      let selectedIds = this.getSelectedIds();
      if (selectedIds.length == 0) {
        this.$message.error({
          content: this.$t("module.role.warning.selectUsers"),
          duration: 3
        });
        return;
      }
      let param = {
        tenantCode: this.tenantCode,
        policyDimensionRelId: this.dimensionId,
        assigneeList: selectedIds
      };
      this.actions[0].loading = true;
      dataPermissionAPI
        .saveAssignedUser(param)
        .then(data => {
          this.$message.success({
            content: this.$t("module.role.warning.assignUserSuccessfully"),
            duration: 3
          });
          this.$emit("Close", true);
        })
        .catch(() => {
          this.actions[0].loading = false;
        });
    },
    getSelectedIds() {
      let list = this.$refs["userTable"].getSelectioned() || [];
      let ids = [];
      for (let { id } of list) {
        ids.push(id);
      }
      return ids;
    }
  },
  watch: {},
  directives: {}
};
</script>
